package jp.sourceforge.akjrcp.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import jp.sourceforge.akjrcp.akj_betas.Akj_betasPlugin;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class ProcessMonitor {
	Log log=LogFactory.getLog(ProcessMonitor.class);
	Process process;
	boolean monitor;
	ProcessPrinter printer;
	public ProcessMonitor(Process process,ProcessPrinter printer){
		this.process=process;
		this.printer=printer;
	}
	public void startMonitor(){
		monitor=true;
		new ErrorMonitor().start();
		new InputMonitor().start();
	}
	BufferedReader inputReader,errorReader;
	
	public class ErrorMonitor extends Thread{
		public void run(){
			InputStream input=process.getErrorStream();
			
			inputReader=new BufferedReader(new InputStreamReader(input));
			String line2;
			try {
				while((line2=inputReader.readLine())!=null){
					printer.printError(line2+"\n");
					//Akj_betasPlugin.getDefault().addLog();
				}
				inputReader.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	public class InputMonitor extends Thread{
		public void run(){
			InputStream input=process.getInputStream();
			
			errorReader=new BufferedReader(new InputStreamReader(input));
			String line2;
			try {
				while((line2=errorReader.readLine())!=null){
					printer.printOutput(line2+"\n");
				}
				errorReader.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public void stop() {
		try {
			inputReader.close();
			errorReader.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
